﻿using BulletSharp;
using ET.HelloWorld.Hotfix.Entitys;
using ETModel;
using PF;
using System.Linq;
using UnityEngine;

namespace ETHotfix
{
	[ActorMessageHandler(AppType.Map)]
	public class Frame_ShootBoxHandler : AMActorLocationHandler<MapPlayer, Frame_ShootBox>
	{
        protected const float shootBoxInitialSpeed = 40;


        protected override void Run(MapPlayer mapPlayer, Frame_ShootBox message) {
            var mapUnitsComp = Game.Scene.GetComponent<UnitsComponent>();
            var cfgComp = Game.Scene.GetComponent<ConfigComponent>();


            //创建一个测试方块,自由落体
            var unit1Cfg = cfgComp.Get<UnitConfig>(1001);
            var pos1 = mapPlayer.GetFirstSelfUnit().GetPosition();
            var unit1Mass = 0.1f;
            GameUnit unit1 = ComponentFactory.CreateWithId<GameUnit, long>(IdGenerater.GenerateId(), mapPlayer.Id);
            unit1.UnitConfigId = unit1Cfg.Id;
            unit1.SetScale(unit1Cfg.GetLocalScale());
            unit1.Center = unit1Cfg.GetCenter();
            unit1.SetPosition(pos1);
            //加入物理引擎
            unit1.AddComponent<BulletCollisionShape, CollisionShape>(unit1Cfg.CreateBulletCollisionShape());
            var bObj = unit1.AddComponent<BulletCollisionObject, float, Vector3, Quaternion>(unit1Mass, unit1.GetPosition(), unit1.GetRotation());
            var unitInfo1 = unit1.BuildUnitInfo();
            //加入到当前玩家的单位管理中
            mapPlayer.AddSelfUnit(unit1);
            //加入客户端调试线框
            Game.Scene.GetComponent<DebugInfoSyncComponent>()?.UpdateGizmosMeshSync(unit1.Id, unitInfo1);

            //同步给所有客户端
            M2C_PlayerEnterMap playerEnterMsg = new M2C_PlayerEnterMap();
            playerEnterMsg.NewUnits.Add(unitInfo1);
            playerEnterMsg.MapBroadcastAllPlayers();

            //发射
            var dir = new Vector3(message.X, message.Y, message.Z).ToBullet();
            dir.Normalize();
            bObj.RigidBody.LinearFactor = new Vector3(1, 1, 1).ToBullet();
            bObj.RigidBody.LinearVelocity = dir * shootBoxInitialSpeed;
            bObj.RigidBody.CcdMotionThreshold = 0.5f;
            bObj.RigidBody.CcdSweptSphereRadius = 0.9f;

            //设置物理对象可以一直接收碰撞
            //unit1.GetBulletCollisionObject().RigidBody.ActivationState = ActivationState.DisableDeactivation;
        }
    }
}